package com.sqs.service.impl;

import com.sqs.constant.RedisConstant;
import com.sqs.service.CommonService;
import com.sqs.utils.AliOssUtil;
import com.sqs.vo.CaptchaVO;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class CommonServiceImpl implements CommonService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * 生成随机验证码
     * @return
     */
    public CaptchaVO createCaptcha() {
        //生成验证码图片
        SpecCaptcha captcha = new SpecCaptcha();//规定验证码大小
        captcha.setCharType(Captcha.TYPE_NUM_AND_UPPER);//规定验证码组成
        //生成UUID作为验证码的key
        UUID key = UUID.randomUUID();
        //将数据存进redis
        stringRedisTemplate.opsForValue().set(RedisConstant.CAPTCHA_HEAD + key, captcha.text().toLowerCase(), 2, TimeUnit.MINUTES);

        return CaptchaVO.builder()
                .key(key.toString())
                .img(captcha.toBase64())
                .build();
    }

    /**
     * 上传文件
     * @param file
     * @return
     * */
    public String upload(MultipartFile file) {
        try {
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String objectName = UUID.randomUUID() + extension;

            return aliOssUtil.uploadByte(file.getBytes(), objectName);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
